package study.我的多线程四种方式.ExecutorService;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/*通过Executors创建指定大小数量线程的线程池ExecutorService对象
 * ExecutorService对象中加入实现了Runnable/Callable接口的类对象
 * 则可以实现JAVA中创建线程
 * 通过Future< Integer> future  = executorService.submit(callableTest2);得到每个线程的返回值。
 * 注意：如果ExecutorService线程池中加入的是实现无返回值的Runnable接口类，则无法获取线程返回值，因为Runnable接口类本身无返回值
 */
public class ExecutorServiceTest {

	public static void main(String[] args) {
		int poolSize=9;
		ExecutorService executorService= Executors.newFixedThreadPool(poolSize);
		ArrayList<Future> futures = new ArrayList<Future>(); 		
		for (int i = 0; i < poolSize; i++) {
			CallableTest2 callableTest2=new CallableTest2(i);
			Future< Integer> future  = executorService.submit(callableTest2);
			futures.add(future);
		}
		executorService.shutdown();
		
		//输出9个子线程的返回值
		for (int i = 0; i < futures.size(); i++) {
			Future<Integer>  future = futures.get(i);
			try {
				Integer integer =  future.get();
				System.out.println("子线程"+i+"输出:"+integer);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
	}

}
